<script setup>
import {addAddress, getAcquisitionArea, modifyAddress} from "@/api/address.js";
import { showToast } from 'vant';
import { Picker } from 'vant';
import {useI18n} from 'vue-i18n';

const {t} = useI18n();
const openValue = ref(false);

function cancel(e) {
  restForm()
  openValue.value = false;
};

// 重置数据
function restForm() {
  countryList.value = []
  provinceList.value = []
  formData.value = {}
  formRef.value?.resetValidation();
}

const email = ref('')
const password = ref('')

function show(item) {
  restForm()
  if (item) {
    formData.value = JSON.parse(JSON.stringify(item));
  }
  getCountryRegion()
  openValue.value = true
}

// 提交表单
const formData = ref({})
const formRef = ref()

const submitLoading = ref(false)
function submit() {
  formRef.value.validate().then(() => {
    submitLoading.value = true
    if (formData.value.addressId) {
      modifyAddress(formData.value).then((res) => {
        showToast(t('addressManagement.editSuccessful'))
        submitLoading.value = false
        openValue.value = false;
        emit('rest')
      }).catch(() => {
        submitLoading.value = false
        showToast(t('addressManagement.editFailed'))
      })
    } else {
      addAddress(formData.value).then((res) => {
        showToast(t('addressManagement.addSuccessful'))
        submitLoading.value = false
        openValue.value = false;
        emit('rest')
      }).catch(() => {
        submitLoading.value = false
        showToast(t('addressManagement.addFailed'))
      })
    }
  }).catch(error => {
    console.log('error', error);
  });
}

// 获取国家地区
const countryList = ref([]) // 国家列表
const countryFieldName = {
  text: 'name',
  value: 'regionId',
  children: null,
};
function getCountryRegion() {
  getAcquisitionArea().then((res) => {
    countryList.value = res.data
    if (formData.value.addressId) {
      const selectedCountry = countryList.value.find(country => country.regionId === formData.value.countryId);
      if (selectedCountry) {
        provinceList.value = selectedCountry.children;
      }
    }
  })
}

// 选择国家
const showPicker = ref(false)
const provinceList = ref([]) // 省州列表数据
function changeCountry(data) {
  const { selectedValues } = data
  formData.value.countryId = selectedValues[0];
  formData.value.province = ''
  formData.value.provinceId = null
  const selectedCountry = countryList.value.find(country => country.regionId === selectedValues[0]);
  if (selectedCountry) {
    formData.value.country = selectedCountry.name
    provinceList.value = selectedCountry.children;
  }
  showPicker.value = false
}

// 选择省份/州
const showProvincePicker = ref(false)

function clickShowProvincePicker() {
  if (!formData.value.country || formData.value.country === '') {
    showToast(t('addressManagement.selectCountry'))
  } else {
    showProvincePicker.value = true
  }
}

function changeProvince(data) {
  const { selectedValues } = data
  formData.value.provinceId = selectedValues[0]
  const selectedProvince = provinceList.value.find(province => province.regionId === selectedValues[0]);
  if (selectedProvince) {
    formData.value.province = selectedProvince.name
  }
  showProvincePicker.value = false
}

const emit = defineEmits(['rest'])
defineExpose({
  show
})
</script>

<template>
  <van-popup
      v-model:show="openValue"
      :style="{ padding: '24px', width: '85%' }">
      <div class="add-address">
        <h3>{{ formData.addressId ? t('addressManagement.modifyAddress') : t('addressManagement.addAddress') }}</h3>
        <div class="add-address-form">
          <van-form
              ref="formRef"
              validate-trigger="['onSubmit']"
          >
            <c-input
                name="firstName"
                v-model:value="formData.firstName"
                :placeholder="`${$t('addressManagement.firstName')}*`"
                :rules="[
                  { required: true, message: $t('addressManagement.inputName')}
              ]"
            />
            <c-input
                name="lastName"
                v-model:value="formData.lastName"
                :placeholder="`${$t('addressManagement.lastName')}*`"
                :rules="[
                  { required: true, message: $t('addressManagement.inputSurname')}
              ]"
            />
            <c-input
                name="phone"
                v-model:value="formData.phone"
                :placeholder="`${$t('addressManagement.mobilePhoneNumber')}*`"
                :rules="[
                  { required: true, message: $t('addressManagement.inputPhoneNumber')}
              ]"
            />
            <c-input
                name="detail"
                v-model:value="formData.detail"
                :placeholder="`${$t('addressManagement.detailedAddress')}*`"
                :rules="[
                  { required: true, message: $t('addressManagement.inputDetailAddress')}
              ]"
            />
            <c-input
                name="city"
                v-model:value="formData.city"
                :placeholder="`${$t('addressManagement.city')}*`"
                :rules="[
                  { required: true, message: $t('addressManagement.inputCity')}
              ]"
            />
            <div class="select-box" :class="{borderH: formData.country && formData.country !== ''}">
              <van-field
                  v-model="formData.country"
                  is-link
                  readonly
                  :placeholder="!formData.country ? `${t('addressManagement.nation')}*` : ''"
                  @click="showPicker = true"
                  :rules="[
                  { required: true, message: $t('addressManagement.selectCountry')}
              ]"
              />
            </div>
            <van-popup v-model:show="showPicker" round position="center" :style="{ padding: '24px', width: '85%' }">
              <van-picker
                  :columns="countryList"
                  :columns-field-names="countryFieldName"
                  @cancel="showPicker = false"
                  @confirm="changeCountry"
              />
            </van-popup>

            <div class="select-box" :class="{borderH: formData.province && formData.province !== ''}">
              <van-field
                  v-model="formData.province"
                  is-link
                  readonly
                  :placeholder="!formData.province ? `${t('addressManagement.provinceState')}*` : ''"
                  @click="clickShowProvincePicker"
                  :rules="[
                  { required: true, message: $t('addressManagement.selectProvince')}]"
              />
            </div>
            <van-popup v-model:show="showProvincePicker" round position="center" :style="{ padding: '24px', width: '85%' }">
              <van-picker
                  :columns="provinceList"
                  :columns-field-names="countryFieldName"
                  @cancel="showProvincePicker = false"
                  @confirm="changeProvince"
              />
            </van-popup>
            <c-input
                name="postCode"
                v-model:value="formData.postCode"
                :placeholder="`${$t('addressManagement.postcode')}*`"
                :rules="[
                  { required: true, message: $t('addressManagement.inputPostcode')}
              ]"
            />
            <div class="btn-box">
              <van-button class="add-btn s-btn" @click="openValue = false">{{t('addressManagement.cancel')}}</van-button>
              <van-button :loading="submitLoading" class="s-btn" @click="submit">{{t('addressManagement.affirm')}}</van-button>
            </div>
          </van-form>
        </div>
      </div>
    </van-popup>
</template>

<style scoped lang="scss">
.add-address {
  h3 {
    width: 100%;
    margin: 0 auto 20px auto;
    text-align: center;
    font-size: 14px;
  }

  .add-address-form {
    .save-btn {
      width: 100px;
      height: 44px;
      color: #ffffff;
      background: #262626;
      margin-bottom: 40px;
    }
  }
  .e-cell {
    position: relative;
  }
  :deep(.e-input) {
    height: 44px;
  }
  :deep(.ant-input-affix-wrapper) {
    height: 58px;
    margin-bottom: 5px;
  }
  :deep(.p-item ) {
    margin-bottom: 0;
  }
  :deep(.add-address-form ) {
    .ant-select-selector {
      height: 44px;
      display: flex;
      align-items: center;
    }
  }
  .select-box {
    border: 1px solid #E5E5E5;
    margin-bottom: 20px;
  }
  .borderH {
    border: 1px solid #262626;
  }
  .btn-box {
    display: flex;
    justify-content: space-between;
    button {
      width: 48%;
      height: 44px;
    }
  }
}
</style>
